<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Bitly
 *
 * Uses the BitLy API to do things associated with it
 *
 * @author Simon Emms <simon@simonemms.com>
 * @link http://code.google.com/p/bitly-api/wiki/ApiDocumentation
 */
class Bitly {
    /**
     * In Cache
     *
     * Has the URL already been queried?
     * 
     * @param string $long_url
     * @return string/false
     */
    protected function _in_cache($url) {
        /* Get CI instance */
        $objCI = &get_instance();
        $objCI->load->config('bitly');
        
        /* Load the cache driver */
        $objCI->load->driver('cache', array('adapter' => 'file'));
        
        $file = $objCI->config->item('cache_file', 'bitly');
        if($file === false) { $file = 'bitly'; }
        
        /* Query the cache */
        $cache = $objCI->cache->get($file);
        
        if($cache !== false && is_array($cache) && array_key_exists(md5($url), $cache)) {
            return $cache[md5($url)];
        }
        
        return false;
    }
    /**
     * Save Cache
     *
     * Saves the URL to the cache
     * 
     * @param string $long_url
     * @param string $short_url
     */
    protected function _save_cache($url, $bitly) {
        
        $objCI = &get_instance();

        $file = $objCI->config->item('cache_file', 'bitly');

        $objCI->load->driver('cache', array('adapter' => 'file'));

        $cache = $objCI->cache->get($file);

        $arrData = array();

        /* Check if anything exists */
        if($cache !== false) {
            /* Something already in here */
            if(is_array($cache)) {
                $arrData = $cache;
            }
        }

        $arrData[md5($url)] = $bitly;

        /* Save for three months as BitLy URLs never expire */
        $expire = 60 * 60 * 24 * 90;

        $objCI->cache->save($file, $arrData, $expire);
    }
    /**
     * Shorten
     *
     * Shortens a URL using the BitLy API
     *
     * @param string $long_url
     * @return string
     * @link http://code.google.com/p/bitly-api/wiki/ApiDocumentation#/v3/shorten
     */
    public function shorten($url) {
        
        $return = $this->_in_cache($url);
        
        if($return === false) {
            
            /* Not cached - get from BitLy */
            $objCI = &get_instance();
            $objCI->load->config('bitly');
            
            /* What we need */
            $arrConfig = array('login', 'apiKey', 'format');
            
            /* Begin the URL query */
            $query = $objCI->config->item('url', 'bitly');
            
            foreach($arrConfig as $id => $config) {
                $value = $objCI->config->item($config, 'bitly');
                
                if($value !== false) {
                    /* Add to query */
                    if($id > 0) { $query .= '&'; }
                    $query .= "{$config}={$value}";
                } else {
                    /* String invalid - throw error */
                    show_error("BitLy {$config} is invalid");
                }
            }
            
            /* Finally, add the URL */
            $query .= "&longUrl=".urlencode($url);
            
            /* Query using file get contents */
            $return = file_get_contents($query);
            
            /* Cache it */
            $this->_save_cache($url, $return);
        }
        return $return;
        
    }
}

?>